/**
 * Copyright (c) 2006 George Malamidis, nutrun.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this
 * software and associated documentation files (the "Software"), to deal in the Software
 * without restriction, including without limitation the rights to use, copy, modify,
 * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies
 * or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
 * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * $Author$
 * $Rev$
 */

package aerie.server;

import aerie.servlet.AerieFilter;
import org.mortbay.jetty.Handler;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.webapp.WebAppContext;

import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class Localhost {
    private static final String WEBAPP_ROOT = ".";

    private final Server server;

    public static void main(String[] args) throws Exception {
        Localhost localhost = new Localhost();
        if (args.length > 0 && args[0].equalsIgnoreCase("--stop")) {
            System.out.println("STOPPING JETTY");
            localhost.stop();
        } else {
            System.out.println("STARTING JETTY");
            localhost.server.start();
            System.out.println(localhost.jettyStartedMessage());
            Monitor.monitor();
        }
    }

    private Localhost() {
        server = new Server(getPort());
        server.addHandler(context());
    }

    private WebAppContext context() {
        WebAppContext context = new WebAppContext(WEBAPP_ROOT, getContextPath());
        context.addFilter(AerieFilter.class, "/*", Handler.DEFAULT);
        return context;
    }

    private void stop() throws Exception {
        //noinspection UnnecessaryUnboxing
        int port = Integer.getInteger("STOP.PORT", -1).intValue();
        String key = System.getProperty("STOP.KEY", null);
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), port);
        OutputStream out = socket.getOutputStream();
        out.write((key+"\r\nstop\r\n").getBytes());
        out.flush();
        out.close();
    }

    private int getPort() {
        String portProp = System.getProperty("jetty.port");
        return (portProp != null) ? Integer.parseInt(portProp) : 8080;
    }

    private String getContextPath() {
        String contextPathProp = System.getProperty("jetty.context");
        return (contextPathProp != null)  ? contextPathProp : "/";
    }

    private String jettyStartedMessage() throws UnknownHostException {
        String addr = InetAddress.getLocalHost().getCanonicalHostName();
        int port = getPort();
        String contextPath = getContextPath();
        return "Application started on "+ "http://" + addr + ":" + port + contextPath;
    }

}